package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.alibaba.fastjson.JSON;
import com.aliyun.facebody20191230.models.ListFaceDbsResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.FocusApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Focus;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoCommentsVo;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SmallVideosService {

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    @DubboReference
    private FocusApi focusApi;

    /**
     * 上传视频
     *
     * @param videoThumbnail 封面图片文件
     * @param videoFile      视频文件
     */
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {

        if (videoFile.isEmpty() || videoThumbnail.isEmpty()) {
            throw new BusinessException(ErrorResult.error());
        }

        //1、将视频上传到FastDFS,获取访问URL
        String filename = videoFile.getOriginalFilename();  // abc.mp4
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), filename, null);
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        //2、将封面图片上传到阿里云OSS，获取访问的URL
        String imageUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        //3、构建Videos对象
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(imageUrl);
        video.setVideoUrl(videoUrl);
        video.setText("我就是我，不一样的烟火");
        //4、调用API保存数据
        String videoId = videoApi.save(video);
        if (StringUtils.isEmpty(videoId)) {
            throw new BusinessException(ErrorResult.error());
        }

        //发送消息
        mqMessageService.sendLogMessage(UserHolder.getUserId(), "0301", "video", videoId);
    }

    //查询视频列表
    @Cacheable(
            value = "videos",
            key = "T(com.tanhua.server.interceptor.UserHolder).getUserId()+'_'+#page+'_'+#pagesize")
//userid _ page_pagesize
    public PageResult queryVideoList(Integer page, Integer pagesize) {
        //获取userId
        Long userId = UserHolder.getUserId();
        //1、查询redis数据
        String redisKey = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        String redisValue = (String) redisTemplate.opsForValue().get(redisKey);
        //2、判断redis数据是否存在，判断redis中数据是否满足本次分页条数
        List<Video> list = new ArrayList<>();
        int redisPages = 0;
        if (!StringUtils.isEmpty(redisValue)) {
            //3、如果redis数据存在，根据VID查询数据
            String[] values = redisValue.split(",");
            //判断当前页的起始条数是否小于数组总数
            if ((page - 1) * pagesize < values.length) {
                List<Long> vids = Arrays.stream(values).skip((page - 1) * pagesize).limit(pagesize)
                        .map(e -> Long.valueOf(e))
                        .collect(Collectors.toList());
                //5、调用API根据PID数组查询动态数据
                list = videoApi.findMovementsByVids(vids);
            }
            redisPages = PageUtil.totalPage(values.length, pagesize);
        }
        //4、如果redis数据不存在，分页查询视频数据
        if (list.isEmpty()) {
            //page的计算规则，  传入的页码  -- redis查询的总页数
            list = videoApi.queryVideoList(page - redisPages, pagesize);  //page=1 ?
        }
        //5、提取视频列表中所有的用户id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        //6、查询用户信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);

        //7、构建返回值
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            UserInfo info = map.get(video.getUserId());
            Boolean member = redisTemplate.boundSetOps("gz" + userId).isMember(info.getId());
            if (info != null) {
                VideoVo vo = VideoVo.init(info, video);
                //判断是否关注该用户
                if (member){
                    vo.setHasFocus(1);
                }
                vos.add(vo);
            }
        }
        return new PageResult(page, pagesize, 0l, vos);
    }




    public void userFocus(Long toUserId) {
        //获得用户id
        Long userId = UserHolder.getUserId();
        //构建对象
        Focus focus = new Focus();
        focus.setUserId(userId);
        focus.setToUserId(toUserId);
        focus.setCreateDate(new SimpleDateFormat("yyyyMMdd").format(new Date()));
        //添加关注的用户信息
        focusApi.save(focus);
        //将对象信息存到redis中
        redisTemplate.boundSetOps("gz" + userId).add(toUserId);
    }

    public void userUnFocus(Long toUserId) {
        //获得用户id
        Long userId = UserHolder.getUserId();
        //删除关注的用户信息
        focusApi.delete( userId, toUserId);
        //将对象信息从redis中删除
        redisTemplate.boundSetOps("gz" + userId).remove(toUserId);
    }


    //视频点赞
    //添加点赞的时候 id就是被点赞人的id, 值就是当前用户的id
    public void SpLike(String ids) {
        //获取视频id
        ObjectId id = new ObjectId(ids);

        //获取视频发布人的id
        Video v = videoApi.selectById(id);

        //获取当前用户的id
        Long userId = UserHolder.getUserId();

        Boolean isEmpty = redisTemplate.boundSetOps("spdz" + v.getUserId()).isMember(userId);

        if (isEmpty) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //修改点赞数量
        boolean boo = videoApi.update(id);
        if (!boo) {
            throw new BusinessException(ErrorResult.disLikeError());
        }

        //redis添加
        BoundSetOperations keys = redisTemplate.boundSetOps("spdz" + v.getUserId());
        keys.add(userId);
    }

    //视频点赞 取消
    public void dislike(String ids) {
        //获取视频id
        ObjectId id = new ObjectId(ids);

        //获取视频发布人的id
        Video v = videoApi.selectById(id);

        //获取当前用户的id
        Long userId = UserHolder.getUserId();

        Boolean isEmpty = redisTemplate.boundSetOps("spdz" + v.getUserId()).isMember(userId);

        if (!isEmpty) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //修改点赞数量
        boolean boo = videoApi.updatej(id);
        if (!boo) {
            throw new BusinessException(ErrorResult.disLikeError());
        }

        //redis删除
        redisTemplate.boundSetOps("spdz" + v.getUserId()).remove(userId);
    }

    //视频评论列表
    public PageResult comments(String ids, Integer page, Integer pagesize) {
        PageResult p = new PageResult();

        //获取视频id
        ObjectId id = new ObjectId(ids);


        Video video = videoApi.selectById(id);
        //根据用户id获取所有视频评论
        List<Comment> list = commentApi.selectsss(id, 9, page, pagesize);
        if (list == null && list.size() <= 0) {
            p.setPagesize(pagesize);
            p.setPage(page);
            p.setCounts(0l);
            p.setItems(new ArrayList<>());
            p.setPages(1l);
        }
        List<Long> l = new ArrayList<>();
        for (Comment c : list) {
            Long userId = c.getUserId();
            l.add(userId);
        }
        List<VideoCommentsVo> vos = new ArrayList<>();
        VideoCommentsVo vo = null;
        //根据用户id查询详细信息
        Map<Long, UserInfo> byIds = userInfoApi.findByIds(l, null);
        for (Comment c : list) {
            UserInfo userInfo = byIds.get(c.getUserId());
            if (userInfo != null) {
                vo = new VideoCommentsVo();
                vo.setAvatar(userInfo.getAvatar());
                vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd kk:mm:ss").format(new Date(c.getCreated())));
                vo.setNickname(userInfo.getNickname());
                vo.setId(c.getId().toString());
                vo.setContent(c.getContent());
                vo.setLikeCount(c.getLikeCount());

                Boolean isEmpty = redisTemplate.boundSetOps("pldz" + c.getId()).isMember(UserHolder.getUserId());
                if (isEmpty) {
                    vo.setHasLiked(1);
                }
                vo.setHasLiked(0);
                vos.add(vo);
            }
        }
        p.setPagesize(pagesize);
        p.setPage(page);
        p.setCounts(Long.valueOf(vos.size()));
        p.setItems(vos);
        p.setPages(Long.valueOf(vos.size() / pagesize));
        return p;
    }

    //评论发布
    public void comm(String sId, Map map) {
        ObjectId id = new ObjectId(sId); //视频id

        String comment = (String) map.get("comment"); //评论正文

        //获取被评论人id
        Video video = videoApi.selectById(id);

        Comment c = new Comment();
        c.setPublishId(id);
        c.setCommentType(9);
        c.setContent(comment);
        c.setUserId(UserHolder.getUserId());
        c.setPublishUserId(video.getUserId());
        c.setCreated(System.currentTimeMillis());

        commentApi.saves(c);
    }

    //视频评论点赞
    public void commentsLike(String ids) {
        //获取视频id
        ObjectId id = new ObjectId(ids);

        //获取本视频的发布者
        Comment c = commentApi.selectt(id);

        //判断该评论本用户是否点赞
        Boolean boo = redisTemplate.boundSetOps("sppldz" + id).isMember(UserHolder.getUserId());
        if (boo){
            throw new BusinessException(ErrorResult.likeError());
        }

        //给评论点赞数加一
        boolean b = commentApi.update(c);
        if (!b){
            throw new BusinessException(ErrorResult.error());
        }

        redisTemplate.boundSetOps("sppldz" + id).add(UserHolder.getUserId());
    }

    //评论点赞取消
    public void commentsDislike(String ids) {
        //获取视频id
        ObjectId id = new ObjectId(ids);

        //获取本视频的发布者
        Comment c = commentApi.selectt(id);

        //判断该评论本用户是否点赞
        Boolean boo = redisTemplate.boundSetOps("sppldz" + id).isMember(UserHolder.getUserId());
        if (!boo){
            throw new BusinessException(ErrorResult.disLikeError());
        }

        //给评论点赞数减一
        boolean b = commentApi.updates(c);
        if (!b){
            throw new BusinessException(ErrorResult.error());
        }
        redisTemplate.boundSetOps("sppldz" + id).remove(UserHolder.getUserId());
    }


}
